import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import numpy as np
import matplotlib.pyplot as plt
import random
from collections import deque
import os
import time

'''加了mec时延能耗，改为SAC算法'''
SEED = 45
torch.manual_seed(SEED)
torch.cuda.manual_seed(SEED)
np.random.seed(SEED)
random.seed(SEED)

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print(f"Using device: {device}")
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False

EPISODES_PER_TASK = 200  # 【修改】与代码一保持一致，便于比较

# 环境参数
AREA_SIZE = 100
NUM_USERS = 10
MAX_STEPS = 200
MAX_DISTANCE_COLLECT = 15

# UAV参数
UAV_HEIGHT = 30.0
UAV_SPEED = 10.0  # 【修改】与代码一保持一致，便于比较
UAV_COMPUTE_CAPACITY = 1e10

# SAC参数
ACTOR_LR = 3e-4
CRITIC_LR = 3e-4
ALPHA_LR = 3e-4  # 【新增】温度参数学习率
GAMMA = 0.99
TAU = 0.005
BUFFER_SIZE = 200000
BATCH_SIZE = 256
EXPLORATION_NOISE_START = 0.4
EXPLORATION_NOISE_END = 0.05
REWARD_SCALE = 0.1
# SAC特有参数
INIT_ALPHA = 0.2  # 【新增】初始熵温度
TARGET_ENTROPY = -2.0  # 【新增】目标熵，通常设为 -action_dim

# EWC参数
EWC_LAMBDA = 1.0
FISHER_SAMPLE_SIZE = 1000

# GRU参数
SEQUENCE_LENGTH = 10
HIDDEN_SIZE = 128

# 通信参数
BANDWIDTH = 1e6
USER_TRANSMIT_POWER = 0.1
CHANNEL_GAIN_REF_DB = 30.0
CHANNEL_GAIN_REF_LINEAR = 10 ** (CHANNEL_GAIN_REF_DB / 10)
PATH_LOSS_EXPONENT = 2.5
BOLTZMANN_CONSTANT = 1.38e-23
TEMPERATURE_KELVIN = 290
NOISE_POWER = BOLTZMANN_CONSTANT * TEMPERATURE_KELVIN * BANDWIDTH
RICE_FACTOR = 5

# 任务参数
TASK_SIZE_BITS = [1e6, 2e6]
TASK_CPU_CYCLES = [5e8, 15e8]

# 【新增】UAV飞行能耗模型参数 (基于旋翼无人机)
UAV_WEIGHT_KG = 2.0  # 无人机重量 (kg)
GRAVITY = 9.81  # 重力加速度 (m/s^2)
AIR_DENSITY = 1.225  # 空气密度 (kg/m^3)
ROTOR_RADIUS = 0.4  # 旋翼半径 (m)
NUM_ROTORS = 4  # 旋翼数量
P_INDUCED_COEFF = UAV_WEIGHT_KG * GRAVITY * np.sqrt(
    UAV_WEIGHT_KG * GRAVITY / (2 * AIR_DENSITY * np.pi * ROTOR_RADIUS ** 2))  # 悬停感应功率
P_PROFILE_COEFF = 0.012  # 旋翼叶型功率系数
P_PARASITE_COEFF = 0.6  # 寄生阻力系数
EFFECTIVE_SWITCHED_CAPACITANCE = 1e-28  # 有效开关电容 (一个用于计算能耗的系数)

# 权重参数
DELAY_WEIGHT = 0.5  # 时延权重
ENERGY_WEIGHT = 0.5  # 能耗权重
DELAY_SCALE = 10  # 时延缩放因子
ENERGY_SCALE = 0.01  # 能耗缩放因子


class Environment:
    def __init__(self):
        self.user_positions = np.random.uniform(0, AREA_SIZE, size=(NUM_USERS, 2))
        self.task_cpu_cycles = np.random.uniform(TASK_CPU_CYCLES[0], TASK_CPU_CYCLES[1], size=NUM_USERS)
        self.task_sizes = np.random.uniform(TASK_SIZE_BITS[0], TASK_SIZE_BITS[1], size=NUM_USERS)
        self.task_generating_users = np.ones(NUM_USERS, dtype=bool)
        self.uav_position = np.array([AREA_SIZE / 2, AREA_SIZE / 2], dtype=float)
        self.collected_tasks = np.zeros(NUM_USERS, dtype=bool)
        self.step_count = 0

        # 【修改】使用每个用户的完成时延数组，而不是全局总时延
        self.user_completion_delays = np.zeros(NUM_USERS)
        self.user_offloading_delays = np.zeros(NUM_USERS)  # 【新增】卸载时延
        self.user_computation_delays = np.zeros(NUM_USERS)  # 【新增】计算时延
        self.user_computation_energies = np.zeros(NUM_USERS)  # 【新增】每个用户的计算能耗
        self.total_flight_energy = 0  # 【修改】总飞行能耗

        self.trajectory = [self.uav_position.copy()]
        self.last_distances = np.array([np.linalg.norm(self.uav_position - pos) for pos in self.user_positions])
        self.observation_history = deque(maxlen=SEQUENCE_LENGTH)
        self.current_phase = 1

    def _calculate_rice_channel_gain(self, distance_2d):
        distance_3d = np.sqrt(distance_2d ** 2 + UAV_HEIGHT ** 2)
        if distance_3d < 1.0: distance_3d = 1.0
        path_loss = CHANNEL_GAIN_REF_LINEAR * (distance_3d ** (-PATH_LOSS_EXPONENT))
        K = RICE_FACTOR
        h_los = 1.0
        h_nlos_real = np.random.normal(0, 1)
        h_nlos_imag = np.random.normal(0, 1)
        h_nlos = (h_nlos_real + 1j * h_nlos_imag) / np.sqrt(2)
        h = np.sqrt(K / (K + 1)) * h_los + np.sqrt(1 / (K + 1)) * h_nlos
        fading_gain = abs(h) ** 2
        return path_loss * fading_gain

    def _calculate_offloading_delay(self, user_index, distance_2d):
        channel_gain = self._calculate_rice_channel_gain(distance_2d)
        snr = (USER_TRANSMIT_POWER * channel_gain) / NOISE_POWER
        data_rate = BANDWIDTH * np.log2(1 + snr)
        return self.task_sizes[user_index] / data_rate

    # 【新增】计算时延函数
    def _calculate_computation_delay(self, user_index):
        return self.task_cpu_cycles[user_index] / UAV_COMPUTE_CAPACITY

    # 【新增】能耗模型 - 飞行能耗
    def _calculate_flight_energy(self, distance_moved, time_delta=1.0):
        speed = distance_moved / time_delta
        # 旋翼无人机功率模型 P(v) = P_induced + P_profile + P_parasite
        power = P_INDUCED_COEFF * (
                np.sqrt(1 + (speed ** 4) / (4 * P_INDUCED_COEFF ** 2)) - (speed ** 2) / (2 * P_INDUCED_COEFF)) \
                + P_PROFILE_COEFF * (1 + 3 * (speed ** 2)) \
                + 0.5 * P_PARASITE_COEFF * AIR_DENSITY * speed ** 3
        return power * time_delta

    # 【新增】能耗模型 - 计算能耗
    def _calculate_computation_energy(self, user_index):
        return EFFECTIVE_SWITCHED_CAPACITANCE * self.task_cpu_cycles[user_index]

    def update_task_generating_users(self, phase):
        self.current_phase = phase
        if phase == 1:
            self.task_generating_users = np.ones(NUM_USERS, dtype=bool)
        elif phase == 2:
            indices = np.random.choice(NUM_USERS, 9, replace=False)
            self.task_generating_users = np.zeros(NUM_USERS, dtype=bool)
            self.task_generating_users[indices] = True
        else:
            indices = np.random.choice(NUM_USERS, 8, replace=False)
            self.task_generating_users = np.zeros(NUM_USERS, dtype=bool)
            self.task_generating_users[indices] = True
        print(f"Phase {phase}: {sum(self.task_generating_users)} users are generating tasks")
        print(f"Task generating users: {np.where(self.task_generating_users)[0]}")

    def reset(self):
        self.uav_position = np.array([AREA_SIZE / 2, AREA_SIZE / 2], dtype=float)
        self.collected_tasks = np.zeros(NUM_USERS, dtype=bool)
        self.step_count = 0

        # 【修改】重置时延和能耗
        self.user_completion_delays.fill(0)
        self.user_offloading_delays.fill(0)
        self.user_computation_delays.fill(0)
        self.user_computation_energies.fill(0)  # 【新增】
        self.total_flight_energy = 0  # 【修改】

        self.trajectory = [self.uav_position.copy()]
        self.last_distances = np.array([np.linalg.norm(self.uav_position - pos) for pos in self.user_positions])
        self.observation_history.clear()
        initial_state = self._get_state()
        for _ in range(SEQUENCE_LENGTH):
            self.observation_history.append(initial_state)
        return self._get_gru_state()

    # In class Environment:
    def step(self, action):
        action = np.clip(action, -1, 1)
        movement = action * UAV_SPEED
        prev_position = self.uav_position.copy()
        self.uav_position += movement
        self.uav_position = np.clip(self.uav_position, 0, AREA_SIZE)
        self.trajectory.append(self.uav_position.copy())

        distance_moved = np.linalg.norm(self.uav_position - prev_position)
        flight_energy_step = self._calculate_flight_energy(distance_moved)
        self.total_flight_energy += flight_energy_step

        new_distances = np.array([np.linalg.norm(self.uav_position - pos) for pos in self.user_positions])

        newly_collected = 0
        # 注意：这里我们只传递新距离和旧距离，不再需要传递collected_indices
        # 因为奖励函数可以从环境状态 self.collected_tasks 中获取所需信息

        for i in range(NUM_USERS):
            if self.task_generating_users[i] and not self.collected_tasks[i]:
                if new_distances[i] <= MAX_DISTANCE_COLLECT:
                    self.collected_tasks[i] = True
                    newly_collected += 1

                    # 当任务被收集时，立即计算其时延和计算能耗
                    offloading_delay = self._calculate_offloading_delay(i, new_distances[i])
                    computation_delay = self._calculate_computation_delay(i)
                    self.user_offloading_delays[i] = offloading_delay
                    self.user_computation_delays[i] = computation_delay
                    self.user_completion_delays[i] = offloading_delay + computation_delay
                    self.user_computation_energies[i] = self._calculate_computation_energy(i)

        self.step_count += 1

        # 【核心修改】计算已完成任务的累计总时延和总能耗
        completed_indices = np.where(self.collected_tasks & self.task_generating_users)[0]

        if len(completed_indices) > 0:
            # 总时延 = 所有已完成任务的(卸载时延 + 计算时延)之和
            total_delay = np.sum(self.user_completion_delays[completed_indices])
            # 总计算能耗 = 所有已完成任务的计算能耗之和
            total_comp_energy = np.sum(self.user_computation_energies[completed_indices])
            # 用于日志显示的平均值
            avg_total_delay = np.mean(self.user_completion_delays[completed_indices])
            avg_offloading_delay = np.mean(self.user_offloading_delays[completed_indices])
            avg_computation_delay = np.mean(self.user_computation_delays[completed_indices])
        else:
            total_delay = 0.0
            total_comp_energy = 0.0
            avg_total_delay, avg_offloading_delay, avg_computation_delay = 0.0, 0.0, 0.0

        # 总能耗 = 总飞行能耗 + 总计算能耗
        total_energy = self.total_flight_energy + total_comp_energy

        # 【核心修改】将正确的总能耗和总时延传入奖励函数
        reward_info = self._calculate_reward_detailed(newly_collected, total_energy, total_delay, new_distances,
                                                      self.last_distances)
        reward = reward_info['total_reward']

        self.last_distances = new_distances

        total_tasks_to_collect = sum(self.task_generating_users)
        collected_required_tasks = sum(self.collected_tasks & self.task_generating_users)
        done = (self.step_count >= MAX_STEPS) or (collected_required_tasks == total_tasks_to_collect)

        self.observation_history.append(self._get_state())

        # 【核心修改】更新返回的info字典，使其包含更准确和详细的信息
        return self._get_gru_state(), reward, done, {
            "collected_required": collected_required_tasks,
            "total_required": total_tasks_to_collect,
            "energy": total_energy,
            "delay": avg_total_delay,  # 日志中显示平均时延
            "reward_breakdown": reward_info,
            "flight_energy": self.total_flight_energy,
            "comp_energy": total_comp_energy,
            "delay_breakdown": {
                "avg_offloading_delay": avg_offloading_delay,
                "avg_computation_delay": avg_computation_delay,
                "avg_total_delay": avg_total_delay,
                "total_delay": total_delay,  # 新增总时延，用于分析
            }
        }

    def _get_state(self):
        # 【修改】状态向量增加任务CPU周期的维度
        state = np.zeros(2 + NUM_USERS * 4 + 1)
        state[0:2] = self.uav_position / AREA_SIZE

        for i in range(NUM_USERS):
            dist = np.linalg.norm(self.uav_position - self.user_positions[i])
            idx = 2 + i * 4
            state[idx] = dist / np.sqrt(2 * AREA_SIZE ** 2)
            state[idx + 1] = float(self.collected_tasks[i])
            state[idx + 2] = float(self.task_generating_users[i])
            # 【新增】将任务所需CPU周期加入状态（归一化）
            state[idx + 3] = self.task_cpu_cycles[i] / TASK_CPU_CYCLES[1]

        state[-1] = self.step_count / MAX_STEPS
        return state

    def _get_gru_state(self):
        while len(self.observation_history) < SEQUENCE_LENGTH:
            self.observation_history.append(self._get_state())
        return np.array(list(self.observation_history))

    # In class Environment:
    def _calculate_reward_detailed(self, newly_collected, total_energy, total_delay, new_distances, old_distances):
        """
        重新设计的奖励函数，体现UAV-MEC的核心优化目标：
        minimize: w_delay * Total_Delay + w_energy * Total_Energy

        参数:
            newly_collected: 本步新收集的任务数
            total_energy: 当前的累计总能耗 (飞行能耗 + 已完成任务的计算能耗)
            total_delay: 当前的累计总时延 (已完成任务的卸载+计算时延之和)
            new_distances: 新的距离数组
            old_distances: 旧的距离数组
        """

        collected_required = sum(self.collected_tasks & self.task_generating_users)
        total_required = sum(self.task_generating_users) if sum(self.task_generating_users) > 0 else 1

        # ================================
        # 1. 引导性奖励 (Shaping Rewards) - 在每一步都计算
        # ================================

        # 任务收集奖励 (鼓励收集)
        collection_reward = newly_collected * 15.0

        # 接近奖励 (鼓励靠近未收集的任务)
        proximity_reward = 0.0
        uncollected_indices = np.where(self.task_generating_users & ~self.collected_tasks)[0]
        if len(uncollected_indices) > 0:
            # 计算与最近的未收集用户的距离变化
            uncollected_distances_old = old_distances[uncollected_indices]
            uncollected_distances_new = new_distances[uncollected_indices]
            closest_user_idx = np.argmin(uncollected_distances_new)
            dist_diff = uncollected_distances_old[closest_user_idx] - uncollected_distances_new[closest_user_idx]
            proximity_reward = dist_diff * 0.3  # 给予靠近最近目标的奖励

        # 持续惩罚 (鼓励尽快完成，避免无意义的盘旋)
        time_penalty = 0.1

        # ================================
        # 2. 目标性奖励 (Objective Reward) - 仅在Episode结束时计算
        # ================================

        objective_penalty = 0.0
        completion_bonus = 0.0

        done = (self.step_count >= MAX_STEPS) or (collected_required == sum(self.task_generating_users))

        if done:
            # 只有在Episode结束时，我们才根据最终性能进行大的奖惩
            if collected_required > 0:
                # 应用缩放因子，使时延和能耗在相似的量级上
                scaled_total_delay = total_delay * DELAY_SCALE
                scaled_total_energy = total_energy * ENERGY_SCALE

                # 计算加权目标函数值 (我们想要最小化这个值)
                objective_value = (DELAY_WEIGHT * scaled_total_delay) + \
                                  (ENERGY_WEIGHT * scaled_total_energy)

                # 将最小化问题转化为最大化奖励问题：目标值越小，惩罚越小
                # 这里的惩罚与收集到的任务数量成反比，鼓励收集更多任务
                objective_penalty = objective_value / collected_required

                # 完成度奖励
                completion_rate = collected_required / total_required
                completion_bonus = completion_rate * 100.0  # 基础完成度奖励

                # 对全部完成给予巨大额外奖励
                if completion_rate == 1.0:
                    completion_bonus += 150.0

            else:  # 如果一个任务都没收集到，给予最大惩罚
                objective_penalty = 200.0  # 一个固定的巨大惩罚

        # 总奖励 = 引导奖励 + 目标奖励
        total_reward = (collection_reward +
                        proximity_reward +
                        completion_bonus -
                        time_penalty -
                        objective_penalty)

        # 最后应用全局缩放因子
        scaled_reward = total_reward * REWARD_SCALE

        return {
            'total_reward': scaled_reward,
            'collection_reward': collection_reward * REWARD_SCALE,
            'proximity_reward': proximity_reward * REWARD_SCALE,
            'completion_bonus': completion_bonus * REWARD_SCALE,
            'objective_penalty': -objective_penalty * REWARD_SCALE,  # 惩罚项记为负
            'time_penalty': -time_penalty * REWARD_SCALE
        }

    def render(self, episode=0, clear_output=True):
        plt.figure(figsize=(10, 10))
        for i, pos in enumerate(self.user_positions):
            if self.task_generating_users[i]:
                color = 'green' if self.collected_tasks[i] else 'red'
            else:
                color = 'gray'
            plt.scatter(pos[0], pos[1], s=100, c=color)
            task_info = f"{i + 1}\n{self.task_sizes[i] / 1e6:.1f}Mb\n{self.task_cpu_cycles[i] / 1e9:.1f}Gcy"
            plt.annotate(task_info, (pos[0], pos[1]), fontsize=8, ha='center', va='bottom')
        trajectory = np.array(self.trajectory)
        plt.plot(trajectory[:, 0], trajectory[:, 1], 'b-', alpha=0.5)
        plt.scatter(self.uav_position[0], self.uav_position[1], s=200, c='blue', marker='*')
        circle = plt.Circle((self.uav_position[0], self.uav_position[1]), MAX_DISTANCE_COLLECT, color='blue',
                            fill=False, alpha=0.3)
        plt.gca().add_patch(circle)
        plt.xlim(0, AREA_SIZE)
        plt.ylim(0, AREA_SIZE)
        title = f"Episode {episode}, Step {self.step_count}\n"
        title += f"收集: {sum(self.collected_tasks & self.task_generating_users)}/{sum(self.task_generating_users)} 任务"
        plt.title(title)
        plt.grid(True)
        plt.savefig(f"results/step_{episode}_{self.step_count}.png")
        plt.close()


# 【重要修改】SAC网络结构
class GRUActor(nn.Module):
    def __init__(self, state_dim, action_dim, max_action):
        super(GRUActor, self).__init__()
        self.state_dim = state_dim
        self.seq_len = SEQUENCE_LENGTH
        self.hidden_size = HIDDEN_SIZE
        self.max_action = max_action
        self.action_dim = action_dim

        self.gru = nn.GRU(input_size=state_dim, hidden_size=self.hidden_size, num_layers=1, batch_first=True)
        self.layer1 = nn.Linear(self.hidden_size, 256)
        self.layer2 = nn.Linear(256, 128)

        # SAC需要输出均值和log标准差
        self.mean_layer = nn.Linear(128, action_dim)
        self.log_std_layer = nn.Linear(128, action_dim)

        self.ln1 = nn.LayerNorm(256)
        self.ln2 = nn.LayerNorm(128)
        self.hidden = None
        self._init_weights()

    def _init_weights(self):
        for m in self.modules():
            if isinstance(m, nn.Linear):
                nn.init.xavier_uniform_(m.weight)
                nn.init.constant_(m.bias, 0.0)

    def forward(self, state, reset_hidden=False):
        batch_size = state.size(0)
        if reset_hidden or self.hidden is None or self.hidden.size(1) != batch_size:
            self.reset_hidden(batch_size)

        gru_out, self.hidden = self.gru(state, self.hidden)
        x = gru_out[:, -1]
        x = self.ln1(torch.relu(self.layer1(x)))
        x = self.ln2(torch.relu(self.layer2(x)))

        mean = self.mean_layer(x)
        log_std = self.log_std_layer(x)
        log_std = torch.clamp(log_std, min=-20, max=2)  # 限制log_std范围

        return mean, log_std

    def sample(self, state, reset_hidden=False):
        mean, log_std = self.forward(state, reset_hidden)
        std = log_std.exp()
        normal = torch.distributions.Normal(mean, std)
        x_t = normal.rsample()  # 重参数化技巧
        y_t = torch.tanh(x_t)
        action = y_t * self.max_action
        log_prob = normal.log_prob(x_t)
        # 修正tanh变换的log概率
        log_prob -= torch.log(self.max_action * (1 - y_t.pow(2)) + 1e-6)
        log_prob = log_prob.sum(1, keepdim=True)
        mean = torch.tanh(mean) * self.max_action
        return action, log_prob, mean

    def reset_hidden(self, batch_size=1):
        self.hidden = torch.zeros(1, batch_size, self.hidden_size).to(device)


class GRUCritic(nn.Module):
    def __init__(self, state_dim, action_dim):
        super(GRUCritic, self).__init__()
        self.state_dim = state_dim
        self.seq_len = SEQUENCE_LENGTH
        self.hidden_size = HIDDEN_SIZE
        self.q1_gru = nn.GRU(input_size=state_dim, hidden_size=self.hidden_size, num_layers=1, batch_first=True)
        self.q2_gru = nn.GRU(input_size=state_dim, hidden_size=self.hidden_size, num_layers=1, batch_first=True)
        self.q1_layer1 = nn.Linear(self.hidden_size + action_dim, 256)
        self.q1_layer2 = nn.Linear(256, 128)
        self.q1_output = nn.Linear(128, 1)
        self.q1_ln1 = nn.LayerNorm(256)
        self.q1_ln2 = nn.LayerNorm(128)
        self.q2_layer1 = nn.Linear(self.hidden_size + action_dim, 256)
        self.q2_layer2 = nn.Linear(256, 128)
        self.q2_output = nn.Linear(128, 1)
        self.q2_ln1 = nn.LayerNorm(256)
        self.q2_ln2 = nn.LayerNorm(128)
        self.q1_hidden = None
        self.q2_hidden = None
        self._init_weights()

    def _init_weights(self):
        for m in self.modules():
            if isinstance(m, nn.Linear):
                nn.init.xavier_uniform_(m.weight)
                nn.init.constant_(m.bias, 0.01)

    def forward(self, state, action, reset_hidden=False):
        batch_size = state.size(0)
        if reset_hidden or self.q1_hidden is None or self.q1_hidden.size(1) != batch_size:
            self.reset_q1_hidden(batch_size)
        if reset_hidden or self.q2_hidden is None or self.q2_hidden.size(1) != batch_size:
            self.reset_q2_hidden(batch_size)

        q1_gru_out, self.q1_hidden = self.q1_gru(state, self.q1_hidden.to(state.device))
        q2_gru_out, self.q2_hidden = self.q2_gru(state, self.q2_hidden.to(state.device))

        q1_state = q1_gru_out[:, -1]
        q2_state = q2_gru_out[:, -1]

        q1_x = torch.cat([q1_state, action], dim=1)
        q2_x = torch.cat([q2_state, action], dim=1)
        q1 = self.q1_ln1(torch.relu(self.q1_layer1(q1_x)))
        q1 = self.q1_ln2(torch.relu(self.q1_layer2(q1)))
        q1 = self.q1_output(q1)
        q2 = self.q2_ln1(torch.relu(self.q2_layer1(q2_x)))
        q2 = self.q2_ln2(torch.relu(self.q2_layer2(q2)))
        q2 = self.q2_output(q2)
        return q1, q2

    def Q1(self, state, action, reset_hidden=False):
        batch_size = state.size(0)
        if reset_hidden or self.q1_hidden is None or self.q1_hidden.size(1) != batch_size:
            self.reset_q1_hidden(batch_size)

        q1_gru_out, self.q1_hidden = self.q1_gru(state, self.q1_hidden.to(state.device))
        q1_state = q1_gru_out[:, -1]
        q1_x = torch.cat([q1_state, action], dim=1)
        q1 = self.q1_ln1(torch.relu(self.q1_layer1(q1_x)))
        q1 = self.q1_ln2(torch.relu(self.q1_layer2(q1)))
        q1 = self.q1_output(q1)
        return q1

    def reset_hidden(self, batch_size=1):
        self.reset_q1_hidden(batch_size)
        self.reset_q2_hidden(batch_size)

    def reset_q1_hidden(self, batch_size=1):
        self.q1_hidden = torch.zeros(1, batch_size, self.hidden_size).to(device)

    def reset_q2_hidden(self, batch_size=1):
        self.q2_hidden = torch.zeros(1, batch_size, self.hidden_size).to(device)


class ReplayBuffer:
    def __init__(self, max_size=BUFFER_SIZE):
        self.buffer = deque(maxlen=max_size)

    def add(self, state, action, reward, next_state, done):
        self.buffer.append((state, action, reward, next_state, done))

    def sample(self, batch_size):
        batch = random.sample(self.buffer, min(len(self.buffer), batch_size))
        state, action, reward, next_state, done = map(np.stack, zip(*batch))
        return state, action, reward, next_state, done

    def __len__(self):
        return len(self.buffer)


class EWC:
    def __init__(self, model, fisher_sample_size=FISHER_SAMPLE_SIZE):
        self.model = model
        self.fisher_sample_size = fisher_sample_size
        self.importance = {}
        self.old_params = {}
        self.fisher_diagonal = {}

    def _calculate_fisher_info(self, replay_buffer):
        fisher = {}
        for name, param in self.model.named_parameters():
            if param.requires_grad:
                fisher[name] = torch.zeros_like(param).to(device)
        self.model.train()
        samples_count = min(self.fisher_sample_size, len(replay_buffer))
        if samples_count <= 0: return fisher
        for _ in range(samples_count):
            states, actions, _, _, _ = replay_buffer.sample(1)
            states = torch.FloatTensor(states).to(device)
            actions = torch.FloatTensor(actions).to(device)
            self.model.zero_grad()
            if isinstance(self.model, GRUActor):
                self.model.reset_hidden(1)
                if hasattr(self.model, 'sample'):  # SAC Actor
                    _, _, mean = self.model.sample(states)
                    loss = ((mean - actions) ** 2).mean()
                else:  # TD3 Actor
                    outputs = self.model(states)
                    loss = ((outputs - actions) ** 2).mean()
            else:
                self.model.reset_hidden(1)
                outputs, _ = self.model(states, actions)
                loss = outputs.mean()
            loss.backward()
            for name, param in self.model.named_parameters():
                if param.requires_grad and param.grad is not None:
                    fisher[name] += param.grad.pow(2) / samples_count
        return fisher

    def store_task_parameters(self, task_id, replay_buffer):
        print(f"Storing parameters for task {task_id} and computing Fisher information matrix")
        self.old_params = {}
        for name, param in self.model.named_parameters():
            if param.requires_grad:
                self.old_params[name] = param.data.clone()
        self.importance = self._calculate_fisher_info(replay_buffer)
        print(f"Stored {len(self.old_params)} parameters and computed Fisher matrices")

    def calculate_ewc_loss(self, lam=EWC_LAMBDA):
        loss = 0
        if not self.old_params or not self.importance: return loss
        for name, param in self.model.named_parameters():
            if name in self.old_params and name in self.importance and param.requires_grad:
                loss += torch.sum(self.importance[name] * (param - self.old_params[name]).pow(2))
        return lam * loss


# 【重要修改】SAC算法实现
class SAC:
    def __init__(self, state_dim, action_dim, max_action):
        self.actor = GRUActor(state_dim, action_dim, max_action).to(device)
        self.actor_optimizer = optim.Adam(self.actor.parameters(), lr=ACTOR_LR)

        self.critic = GRUCritic(state_dim, action_dim).to(device)
        self.critic_target = GRUCritic(state_dim, action_dim).to(device)
        self.critic_target.load_state_dict(self.critic.state_dict())
        self.critic_optimizer = optim.Adam(self.critic.parameters(), lr=CRITIC_LR)

        # SAC特有的熵温度参数
        self.target_entropy = TARGET_ENTROPY
        self.log_alpha = torch.zeros(1, requires_grad=True, device=device)
        self.alpha = self.log_alpha.exp()
        self.alpha_optimizer = optim.Adam([self.log_alpha], lr=ALPHA_LR)

        self.max_action = max_action
        self.memory = ReplayBuffer()
        self.total_it = 0
        self.ewc_actor = EWC(self.actor)
        self.ewc_critic = EWC(self.critic)
        self.current_task = 1

        # 保持噪声调度以保持一致性（虽然SAC不需要显式噪声）
        self.task_noise = {
            1: np.linspace(EXPLORATION_NOISE_START, EXPLORATION_NOISE_END, EPISODES_PER_TASK),
            2: np.linspace(EXPLORATION_NOISE_START * 0.8, EXPLORATION_NOISE_END, EPISODES_PER_TASK),
            3: np.linspace(EXPLORATION_NOISE_START * 0.7, EXPLORATION_NOISE_END, EPISODES_PER_TASK)
        }

        self.actor_scheduler = optim.lr_scheduler.ReduceLROnPlateau(self.actor_optimizer, mode='max', factor=0.5,
                                                                    patience=100, verbose=True)
        self.critic_scheduler = optim.lr_scheduler.ReduceLROnPlateau(self.critic_optimizer, mode='max', factor=0.5,
                                                                     patience=100, verbose=True)

    def select_action(self, state, noise_scale=EXPLORATION_NOISE_START, evaluate=False):
        if len(state.shape) == 2:
            state = np.expand_dims(state, 0)
        state = torch.FloatTensor(state).to(device)

        if evaluate:
            # 评估时使用确定性动作
            with torch.no_grad():
                _, _, action = self.actor.sample(state)
            return action.cpu().data.numpy().flatten()
        else:
            # 训练时使用随机动作
            with torch.no_grad():
                action, _, _ = self.actor.sample(state)
            return action.cpu().data.numpy().flatten()

    def switch_task(self, task_id):
        print(f"\nSwitching to task {task_id}")
        if self.current_task > 0 and len(self.memory) > 0:
            self.ewc_actor.store_task_parameters(self.current_task, self.memory)
            self.ewc_critic.store_task_parameters(self.current_task, self.memory)
        print(f"Clearing replay buffer for new task.")
        self.memory.buffer.clear()
        self.current_task = task_id
        self.actor.reset_hidden()
        self.critic.reset_hidden()
        print(f"Reset GRU states for new task {task_id}")

    def train(self):
        self.total_it += 1
        if len(self.memory) < BATCH_SIZE:
            return {"critic_loss": 0.0, "actor_loss": 0.0, "alpha_loss": 0.0}

        state, action, reward, next_state, done = self.memory.sample(BATCH_SIZE)
        state = torch.FloatTensor(state).to(device)
        action = torch.FloatTensor(action).to(device)
        reward = torch.FloatTensor(reward.reshape(-1, 1)).to(device)
        next_state = torch.FloatTensor(next_state).to(device)
        done = torch.FloatTensor(done.reshape(-1, 1)).to(device)

        # 重置隐藏状态
        self.critic.reset_hidden(BATCH_SIZE)
        self.actor.reset_hidden(BATCH_SIZE)

        with torch.no_grad():
            self.critic_target.reset_hidden(BATCH_SIZE)
            next_state_action, next_state_log_prob, _ = self.actor.sample(next_state)
            qf1_next_target, qf2_next_target = self.critic_target(next_state, next_state_action)
            min_qf_next_target = torch.min(qf1_next_target, qf2_next_target) - self.alpha * next_state_log_prob
            next_q_value = reward + (1 - done) * GAMMA * min_qf_next_target

        # 训练Critic
        qf1, qf2 = self.critic(state, action)
        qf1_loss = F.mse_loss(qf1, next_q_value)
        qf2_loss = F.mse_loss(qf2, next_q_value)
        qf_loss = qf1_loss + qf2_loss

        # 添加EWC正则化
        if self.current_task > 1:
            critic_ewc_loss = self.ewc_critic.calculate_ewc_loss()
            qf_loss += critic_ewc_loss

        self.critic_optimizer.zero_grad()
        qf_loss.backward()
        torch.nn.utils.clip_grad_norm_(self.critic.parameters(), 1.0)
        self.critic_optimizer.step()

        # 训练Actor
        self.actor.reset_hidden(BATCH_SIZE)
        self.critic.reset_q1_hidden(BATCH_SIZE)
        self.critic.reset_q2_hidden(BATCH_SIZE)

        pi, log_pi, _ = self.actor.sample(state)
        qf1_pi, qf2_pi = self.critic(state, pi)
        min_qf_pi = torch.min(qf1_pi, qf2_pi)

        policy_loss = ((self.alpha * log_pi) - min_qf_pi).mean()

        # 添加EWC正则化
        if self.current_task > 1:
            actor_ewc_loss = self.ewc_actor.calculate_ewc_loss()
            policy_loss += actor_ewc_loss

        self.actor_optimizer.zero_grad()
        policy_loss.backward()
        torch.nn.utils.clip_grad_norm_(self.actor.parameters(), 1.0)
        self.actor_optimizer.step()

        # 训练Alpha（熵温度参数）
        alpha_loss = -(self.log_alpha * (log_pi + self.target_entropy).detach()).mean()

        self.alpha_optimizer.zero_grad()
        alpha_loss.backward()
        self.alpha_optimizer.step()

        self.alpha = self.log_alpha.exp()

        # 软更新目标网络
        for param, target_param in zip(self.critic.parameters(), self.critic_target.parameters()):
            target_param.data.copy_(TAU * param.data + (1 - TAU) * target_param.data)

        return {
            "critic_loss": qf_loss.item(),
            "actor_loss": policy_loss.item(),
            "alpha_loss": alpha_loss.item(),
            "alpha": self.alpha.item()
        }

    def update_lr_schedulers(self, reward):
        self.actor_scheduler.step(reward)
        self.critic_scheduler.step(reward)


def train():
    os.makedirs("results", exist_ok=True)
    env = Environment()

    # 【修改】更新状态维度
    state_dim = 2 + NUM_USERS * 4 + 1
    action_dim = 2
    max_action = 1

    agent = SAC(state_dim, action_dim, max_action)  # 【修改】使用SAC而不是TD3
    total_episodes = 600
    episodes_per_task = 200
    eval_freq = 50

    rewards_history = []
    smoothed_rewards = []
    collection_history = []
    energy_history = []
    delay_history = []
    best_reward = -float('inf')
    best_collection = 0
    losses = {"critic": [], "actor": [], "alpha": []}  # 【修改】添加alpha损失

    start_time = time.time()
    for phase in range(1, 4):
        env.update_task_generating_users(phase)
        agent.switch_task(phase)
        phase_noise_base = EXPLORATION_NOISE_START * (0.9 ** (phase - 1))
        phase_noise = np.linspace(phase_noise_base, EXPLORATION_NOISE_END, episodes_per_task)

        for episode in range(1, episodes_per_task + 1):
            global_episode = (phase - 1) * episodes_per_task + episode
            state = env.reset()
            agent.actor.reset_hidden()
            agent.critic.reset_hidden()
            episode_reward = 0
            last_collection = 0
            episode_losses = {"critic": [], "actor": [], "alpha": []}
            current_noise = phase_noise[episode - 1]

            for step in range(1, MAX_STEPS + 1):
                action = agent.select_action(state, noise_scale=current_noise)
                next_state, reward, done, info = env.step(action)
                agent.memory.add(state, action, reward, next_state, done)
                loss_info = agent.train()
                if loss_info:
                    episode_losses["critic"].append(loss_info["critic_loss"])
                    episode_losses["actor"].append(loss_info["actor_loss"])
                    episode_losses["alpha"].append(loss_info["alpha_loss"])
                state = next_state
                episode_reward += reward
                last_collection = info["collected_required"]
                if done:
                    if global_episode % eval_freq == 0:
                        print(f"--- Episode {global_episode} finished. Generating final trajectory plot. ---")
                        env.render(global_episode)
                    break

            rewards_history.append(episode_reward)
            collection_history.append(last_collection)
            energy_history.append(info["energy"])
            delay_history.append(info["delay"])

            if len(rewards_history) >= 10:
                smoothed_rewards.append(np.mean(rewards_history[-10:]))
            else:
                smoothed_rewards.append(episode_reward)
            if episode_losses["critic"]: losses["critic"].append(np.mean(episode_losses["critic"]))
            if episode_losses["actor"]: losses["actor"].append(np.mean(episode_losses["actor"]))
            if episode_losses["alpha"]: losses["alpha"].append(np.mean(episode_losses["alpha"]))
            agent.update_lr_schedulers(episode_reward)

            current_required = info["total_required"]
            collection_ratio = last_collection / current_required if current_required > 0 else 0
            if collection_ratio > best_collection or (
                    collection_ratio == best_collection and episode_reward > best_reward):
                best_reward = episode_reward
                best_collection = collection_ratio
                torch.save(agent.actor.state_dict(), f"results/best_actor_phase_{phase}.pth")

            elapsed_time = time.time() - start_time

            collected_required = info.get("collected_required", 0)
            total_required = info.get("total_required", 1)

            avg_actor_loss = np.mean(episode_losses["actor"]) if episode_losses["actor"] else 0.0
            avg_critic_loss = np.mean(episode_losses["critic"]) if episode_losses["critic"] else 0.0
            avg_alpha_loss = np.mean(episode_losses["alpha"]) if episode_losses["alpha"] else 0.0

            reward_str = ""
            if 'reward_breakdown' in info:
                rb = info['reward_breakdown']
                reward_str = (f"Rwd(C:{rb['collection_reward']:.1f} P:{rb['proximity_reward']:.1f} "
                              f"B:{rb['completion_bonus']:.1f} ObjP:{rb['objective_penalty']:.1f})")

            energy_str = ""
            if 'flight_energy' in info and 'comp_energy' in info:
                energy_str = f"E(F:{info['flight_energy']:.1f} C:{info['comp_energy']:.1f})"

            delay_str = ""
            if 'delay_breakdown' in info:
                db = info['delay_breakdown']
                delay_str = f"D(Tot:{db['total_delay']:.2f}s AvgOff:{db['avg_offloading_delay']:.3f}s)"

            # 【修改】在打印中添加alpha信息
            print(
                f"Phase {phase} Ep {episode:3d}/{episodes_per_task} "
                f"Tasks {collected_required:2d}/{total_required:2d} "
                f"Steps {env.step_count:3d} "
                f"Loss(A/C/α) {avg_actor_loss:.3f}/{avg_critic_loss:.3f}/{avg_alpha_loss:.3f} "
                f"α:{agent.alpha.item():.3f} | "
                f"Total Rwd: {episode_reward:.2f} "
                f"[{reward_str}] | "
                f"Total E: {info.get('energy', 0):.1f} "
                f"[{energy_str}] | "
                f"Avg D: {info.get('delay', 0):.3f}s "
                f"[{delay_str}] | "
                f"Time: {elapsed_time:.1f}s"
            )

            if global_episode % eval_freq == 0 or global_episode == total_episodes:
                # 【修改】增加图表面板宽度，添加alpha损失图
                plt.figure(figsize=(30, 5))

                plt.subplot(1, 6, 1)
                plt.plot(rewards_history, alpha=0.3, color='blue', label='Raw')
                plt.plot(smoothed_rewards, color='red', label='Smoothed')
                plt.axvline(x=episodes_per_task, color='green', linestyle='--', label='Phase 1->2')
                plt.axvline(x=2 * episodes_per_task, color='purple', linestyle='--', label='Phase 2->3')
                plt.title("Reward")
                plt.xlabel("Episode")
                plt.ylabel("Reward")
                plt.legend()
                plt.grid(True)

                plt.subplot(1, 6, 2)
                plt.plot(collection_history)
                plt.axvline(x=episodes_per_task, color='green', linestyle='--')
                plt.axvline(x=2 * episodes_per_task, color='purple', linestyle='--')
                plt.title("Collected Tasks")
                plt.xlabel("Episode")
                plt.ylabel("Number of Tasks")
                plt.grid(True)

                plt.subplot(1, 6, 3)
                plt.plot(energy_history)
                plt.axvline(x=episodes_per_task, color='green', linestyle='--')
                plt.axvline(x=2 * episodes_per_task, color='purple', linestyle='--')
                plt.title("Total Energy")
                plt.xlabel("Episode")
                plt.ylabel("Energy")
                plt.grid(True)

                plt.subplot(1, 6, 4)
                plt.plot(delay_history)
                plt.axvline(x=episodes_per_task, color='green', linestyle='--')
                plt.axvline(x=2 * episodes_per_task, color='purple', linestyle='--')
                plt.title("Avg Delay")
                plt.xlabel("Episode")
                plt.ylabel("Delay (s)")
                plt.grid(True)

                plt.subplot(1, 6, 5)
                if losses["critic"]: plt.plot(losses["critic"], label='Critic Loss')
                if losses["actor"]: plt.plot(losses["actor"], label='Actor Loss')
                if losses["alpha"]: plt.plot(losses["alpha"], label='Alpha Loss')
                plt.axvline(x=episodes_per_task, color='green', linestyle='--')
                plt.axvline(x=2 * episodes_per_task, color='purple', linestyle='--')
                plt.title("Training Loss")
                plt.xlabel("Episode")
                plt.ylabel("Loss")
                plt.legend()
                plt.grid(True)

                # 【新增】Alpha值变化图
                plt.subplot(1, 6, 6)
                alpha_values = []
                for i in range(len(losses["alpha"])):
                    if i < len(losses["alpha"]):
                        alpha_values.append(agent.alpha.item())
                if alpha_values:
                    plt.plot(alpha_values)
                    plt.axvline(x=episodes_per_task, color='green', linestyle='--')
                    plt.axvline(x=2 * episodes_per_task, color='purple', linestyle='--')
                plt.title("Alpha Value")
                plt.xlabel("Episode")
                plt.ylabel("Alpha")
                plt.grid(True)

                plt.tight_layout()
                plt.savefig(f"results/training_curves_episode_{global_episode}.png")
                plt.close()

                torch.save({
                    'actor_state_dict': agent.actor.state_dict(),
                    'critic_state_dict': agent.critic.state_dict(),
                    'alpha': agent.alpha.item(),
                    'log_alpha': agent.log_alpha.item(),
                    'actor_optimizer': agent.actor_optimizer.state_dict(),
                    'critic_optimizer': agent.critic_optimizer.state_dict(),
                    'alpha_optimizer': agent.alpha_optimizer.state_dict(),
                    'episode': global_episode,
                    'phase': phase,
                    'rewards_history': rewards_history,
                    'collection_history': collection_history,
                    'delay_history': delay_history,
                    'best_reward': best_reward,
                    'best_collection': best_collection
                }, f"results/checkpoint_episode_{global_episode}.pt")

        torch.save(agent.actor.state_dict(), f"results/actor_phase_{phase}.pth")
        torch.save(agent.critic.state_dict(), f"results/critic_phase_{phase}.pth")
    print(f"Training completed! Best result: {best_collection * 100:.1f}% tasks, Reward: {best_reward:.2f}")
    return agent, env


def test_and_visualize(agent, env, model_path="results/actor_phase_3.pth", phase=3):
    agent.actor.load_state_dict(torch.load(model_path))
    agent.actor.eval()
    env.update_task_generating_users(phase)
    state = env.reset()
    agent.actor.reset_hidden()
    total_reward = 0
    step_rewards = []
    trajectory = [env.uav_position.copy()]
    collection_times = np.zeros(NUM_USERS)
    collection_order = []
    for step in range(1, MAX_STEPS + 1):
        action = agent.select_action(state, noise_scale=0, evaluate=True)  # 【修改】使用evaluate=True
        trajectory.append(env.uav_position.copy())
        collected_before = env.collected_tasks.copy()
        next_state, reward, done, info = env.step(action)
        for i in range(NUM_USERS):
            if env.task_generating_users[i] and env.collected_tasks[i] and not collected_before[i]:
                collection_times[i] = step
                collection_order.append(i)
        total_reward += reward
        step_rewards.append(reward)
        state = next_state
        if step % 5 == 0 or done:
            env.render(step)
        if done:
            break
    trajectory = np.array(trajectory)
    plt.figure(figsize=(12, 10))
    for i, (x, y) in enumerate(env.user_positions):
        if env.task_generating_users[i]:
            if env.collected_tasks[i]:
                color = 'green'
                plt.scatter(x, y, s=150, c=color, marker='o')
                plt.annotate(f"用户 {i + 1}\n(步数 {int(collection_times[i])})", (x, y), textcoords="offset points",
                             xytext=(0, 10), ha='center', fontsize=10)
            else:
                color = 'red'
                plt.scatter(x, y, s=150, c=color, marker='o')
                plt.annotate(f"用户 {i + 1}\n(未收集)", (x, y), textcoords="offset points", xytext=(0, 10), ha='center',
                             fontsize=10)
        else:
            color = 'gray'
            plt.scatter(x, y, s=100, c=color, marker='o')
            plt.annotate(f"用户 {i + 1}\n(不产生任务)", (x, y), textcoords="offset points", xytext=(0, 10), ha='center',
                         fontsize=10)
    plt.plot(trajectory[:, 0], trajectory[:, 1], 'b-', label='UAV轨迹', alpha=0.7)
    plt.scatter(trajectory[0, 0], trajectory[0, 1], s=200, c='blue', marker='^', label='起点')
    plt.scatter(trajectory[-1, 0], trajectory[-1, 1], s=200, c='purple', marker='*', label='终点')
    for i in range(0, len(trajectory), 10):
        plt.annotate(f"{i}", (trajectory[i, 0], trajectory[i, 1]), fontsize=8, ha='center', va='center',
                     bbox=dict(boxstyle="circle,pad=0.2", fc="white", alpha=0.7))
    for i in range(NUM_USERS):
        if env.task_generating_users[i] and env.collected_tasks[i]:
            step = int(collection_times[i])
            if step < len(trajectory):
                uav_pos = trajectory[step]
                plt.plot([uav_pos[0], env.user_positions[i, 0]], [uav_pos[1], env.user_positions[i, 1]], 'g--',
                         alpha=0.5)
    plt.title(
        f"UAV任务收集轨迹 (阶段{phase}: 收集 {sum(env.collected_tasks & env.task_generating_users)}/{sum(env.task_generating_users)} 任务, 步数: {env.step_count})")
    plt.xlabel("X坐标 (m)")
    plt.ylabel("Y坐标 (m)")
    plt.grid(True)
    plt.legend()
    plt.xlim(0, AREA_SIZE)
    plt.ylim(0, AREA_SIZE)
    plt.savefig(f"results/final_uav_trajectory_phase_{phase}.png")
    plt.close()
    plt.figure(figsize=(15, 5))
    plt.subplot(1, 2, 1)
    plt.plot(step_rewards)
    plt.title("步奖励")
    plt.xlabel("步数")
    plt.ylabel("奖励")
    plt.grid(True)
    plt.subplot(1, 2, 2)
    plt.plot(np.cumsum(step_rewards))
    plt.title("累计奖励")
    plt.xlabel("步数")
    plt.ylabel("累计奖励")
    plt.grid(True)
    plt.tight_layout()
    plt.savefig(f"results/test_rewards_phase_{phase}.png")
    plt.close()
    print(f"\n测试结果 (阶段 {phase}):")
    collected_count = sum(env.collected_tasks & env.task_generating_users)
    total_count = sum(env.task_generating_users)
    percentage = collected_count / total_count * 100 if total_count > 0 else 0
    print(f"收集任务: {collected_count}/{total_count} ({percentage:.1f}%)")
    print(f"总奖励: {total_reward:.2f}")
    print(f"总能耗: {info['energy']:.2f}")
    print(f"总延迟: {info['delay']:.2f}")
    print(f"总步数: {env.step_count}")
    print(f"最终Alpha值: {agent.alpha.item():.3f}")  # 【新增】显示最终Alpha值
    print("\n任务收集详情:")
    collection_indices = [(i, int(collection_times[i])) for i in range(NUM_USERS) if
                          env.task_generating_users[i] and env.collected_tasks[i]]
    collection_indices.sort(key=lambda x: x[1])
    for i, step in collection_indices:
        print(f"用户 {i + 1}: 在步数 {step} 收集")
    for i in range(NUM_USERS):
        if env.task_generating_users[i] and not env.collected_tasks[i]:
            print(f"用户 {i + 1}: 未收集")


if __name__ == "__main__":
    print("开始使用SAC算法训练UAV-MEC任务收集系统...")
    print("=" * 60)
    print("主要改进：")
    print("1. 将TD3算法替换为SAC算法")
    print("2. 自动调节熵温度参数α")
    print("3. 使用重参数化技巧进行策略优化")
    print("4. 保持所有环境参数、episode数量和图表绘制不变")
    print("=" * 60)

    agent, env = train()

    print("\n" + "=" * 60)
    print("训练完成！开始测试各阶段模型性能...")
    print("=" * 60)

    for phase in range(1, 4):
        print(f"\n测试阶段 {phase} 的SAC模型性能:")
        test_and_visualize(agent, env, model_path=f"results/actor_phase_{phase}.pth", phase=phase)

    print("\n" + "=" * 60)
    print("SAC算法的主要优势：")
    print("1. 更好的探索能力：通过熵正则化鼓励探索")
    print("2. 更稳定的训练：避免了TD3的延迟策略更新")
    print("3. 自适应温度参数：自动调节探索与利用的平衡")
    print("4. 更高的样本效率：通过最大熵框架优化学习效率")
    print("=" * 60)
